'use strict'

module.exports = compose

function compose (middleware) {
  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
  for (const fn of middleware) {
    if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
  }

  //请求来了 尾递归函数才会被执行!!!   来一次请求 调用一次尾递归函数 生成一个index闭包
  return function (context, next) {
    let index = -1
    return dispatch(0)

    //来一次请求 有可能调多次dispatch(得看外部next的调用次数)
    function dispatch (i) {
      //避免重复调用多次next  边界情况!!!
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))

      //修改index闭包
      index = i
      //从中间件中取出第(i+1)个中间件函数
      let fn = middleware[i]

      //当middleware中没有中间件函数了 边界情况!!!
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()

      //执行中间件函数
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}
